package com.zhiyun.service.impl;

import com.zhiyun.domain.Role;
import com.zhiyun.mapper.RoleMapper;
import com.zhiyun.service.RoleService;
import com.zhiyun.util.Db;
import com.zhiyun.vo.Result;

/**
 * @author zc
 * @Date 2025/4/29 下午2:22
 */
public class RoleServiceImpl implements RoleService {
    RoleMapper roleMapper = Db.getMapper(RoleMapper.class);
    @Override
    public Result findAll() {
        return Result.ok(roleMapper.selectAll());
    }

    @Override
    public Result insert(Role role) {
        Role oldRole = roleMapper.selectByName(role.getName());
        if (oldRole != null) {
            return Result.fail("该用户类型已经存在");
        }
        int rows = roleMapper.insert(role);
        if (rows > 0) {
            return Result.okMsg("添加成功");
        }
        return Result.fail("添加失败");
    }

    @Override
    public Result update(Role role) {
        Role oldRole = roleMapper.selectByPrimaryKey(role.getId());
        if (oldRole == null) {
            return Result.fail("该类型不存在");
        }
        if (!oldRole.getName().equals(role.getName())) {
            Role role1 = roleMapper.selectByName(role.getName());
            if (role1 != null) {
                return Result.fail("该类型已经存在");
            }
        }
        int rows = roleMapper.updateByPrimaryKey(role);
        if (rows > 0) {
            return Result.okMsg("修改成功");
        }
        return Result.fail("修改失败");
    }

    @Override
    public Result delete(int id) {
        Role role = roleMapper.selectByPrimaryKey(id);
        if (role == null) {
            return Result.fail("该类型不存在");
        }
        int rows = roleMapper.deleteByPrimaryKey(id);
        if (rows > 0) {
            return Result.okMsg("删除成功");
        }
        return Result.fail("删除失败");
    }
}
